package com.atsmart.app.receiver;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Serializable;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.List;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Message;
import android.util.Log;

import com.atsmart.app.BizApp;
import com.atsmart.app.R;
import com.atsmart.app.exception.BizException;
import com.atsmart.app.http.HttpHelper;
import com.atsmart.app.model.CheckDurationInfo;
import com.atsmart.app.model.CommonBody;
import com.atsmart.app.model.PositionShutDownInfo;
import com.atsmart.app.model.ReportHistoryInfo;
import com.atsmart.app.model.ResultInfo;
import com.atsmart.app.sql.ShutDownSqlHelper;
import com.atsmart.app.utils.PrefsUtils;
import com.atsmart.app.utils.StringUtil;
import com.atsmart.app.webservice.ServiceHelper;
import com.atsmart.app.webservice.ServiceHost;
//import com.atsmart.log.UserLog;
import com.google.json.Gson;
import com.google.json.JsonSyntaxException;
import com.google.json.annotations.SerializedName;

/**
 * @author yhl 2013-8-8 下午5:11:26 TODO
 */

public class HistoryReceiver extends BroadcastReceiver {
	private long length = 0;

	@Override
	public void onReceive(Context context, Intent intent) {
		if ((BizApp.getInstance().isNetworkAvailable() || BizApp.getInstance()
				.isWiFiActive()) && BizApp.getInstance().keeping == true) {
			if (BizApp.getInstance().isfinish) {
				try {
					checkSQL();
				} catch (Exception e) {
				}
			}
		}
	}

	/** 判断上次上传是否结束，检测是否需要上传 */
	private void checkSQL() {

		new Thread() {
			public void run() {

				BizApp.getInstance().isfinish = false;// 开始本次上传
				ShutDownSqlHelper psql = new ShutDownSqlHelper();
				psql.open(BizApp.getInstance().getSqlHelper());
				// 汇报失败手动保存sql
				List<PositionShutDownInfo> repos = psql.getAttributePosLit();
//				 Log.e("sql大小", "大小： = " + repos.size());
//				UserLog.getInstance().writelocal("本地sql： = " + repos.size());
				if (repos != null && repos.size() > 0) {
				
					for (int i = 0; i < repos.size(); i++) {
//						 Log.e("汇报失败sql", "内容: = " + repos.get(i).getPos());
						PositionShutDownInfo rep = repos.get(i);
						if (rep.getType() == 3) {
							// 巡检
							try {
								CheckDurationInfo info = ServiceHelper
										.getInstance()
										.postData(
												ServiceHost.reportLocationURL(),
												new Gson().toJson(body()),
												rep.getPos(),
												CheckDurationInfo.class);

								if (info.getResult() == 0) {
//									UserLog.getInstance().writelocal("本地巡检成功： = " + rep.getPos());
									// Log.e("巡检汇报成功", "巡检内容: = "
									// + repos.get(i).getPos());
									psql.deleteById(rep.getId());
									sleep(50);
								} else {
									sleep(50);
									continue;

								}
							} catch (Exception e) {
								e.printStackTrace();
								// try {
								// sleep(50);
								// } catch (InterruptedException e1) {
								// // TODO Auto-generated catch block
								// e1.printStackTrace();
								// }
								continue;

							}

						}
						if (rep.getType() == 8) {
							String pos = rep.getPos();
							String posp = rep.getPos();
							String imagestr = rep.getImagestr();

							// Log.e("图片路径", "图片路径： = " + imagestr);
							if (imagestr != null && !"".equals(imagestr)) {
								String[] imgstrs = imagestr.split(";");
								if (imgstrs.length > 1) {// 多张图片
									try {
										for (int j = 0; j < imgstrs.length; j++) {
											String[] str1 = imgstrs[j]
													.split(",");
											ImgPathInfo iinfo = im(str1[1]);
											if (iinfo.path == null
													|| "".equals(iinfo.path)) {
												break;
											} else {
												int c = posp
														.indexOf("\"item-id\":"
																+ str1[0]);
												if (c == -1) {
													int template = posp
															.indexOf("\"template\":[");
													posp = posp.substring(0,
															template + 12)
															+ "{\"value\":\""
															+ iinfo.path
															+ "\","
															+ "\"item-id\":"
															+ str1[0]
															+ ","
															+ "\"type_id\":4,\"ext-type\":0},"
															+ posp.substring(
																	template + 12,
																	posp.length());
													// Log.e("111 posp",
													// posp.toString());
												} else {
													posp = posp.substring(0,
															c - 2)
															+ iinfo.path
															+ posp.substring(
																	c - 2,
																	posp.length());
													// Log.e("222 posp",
													// posp.toString());
												}
											}
										}
									} catch (Exception e) {
										e.printStackTrace();
										// try {
										// sleep(50);
										// } catch (InterruptedException e1) {
										// // TODO Auto-generated catch block
										// e1.printStackTrace();
										// }
										break;
									}
								} else {// 单张图片
									String[] imagestra = imagestr.split(",");
									try {
										ImgPathInfo iinfo = im(imagestra[1]);
										if (iinfo.path == null
												|| "".equals(iinfo.path)) {
											continue;
										} else {
											int c = posp.indexOf("\"item-id\":"
													+ imagestra[0]);
											posp = pos.substring(0, c - 2)
													+ iinfo.path
													+ pos.substring(c - 2,
															pos.length());
										}
									} catch (Exception e) {
										e.printStackTrace();
										// try {
										// sleep(50);
										// } catch (InterruptedException e1) {
										// // TODO Auto-generated catch block
										// e1.printStackTrace();
										// }
										continue;
									}

								}
							}
							// 直接汇报保存记录
							try {
//								Log.e("上传 == 8", posp.toString());
								ResultInfo result = ServiceHelper.getInstance()
										.postData(ServiceHost.upload(),
												posp.toString(),
												ResultInfo.class);
								if (result.result == 0) {
//									Log.e("上传成功", posp.toString());
									ReportHistoryInfo history = new ReportHistoryInfo();
									history.name = rep.getReportname();
									history.date = StringUtil.getReportTime();
									history.type = rep.getReporttype();
									BizApp.getInstance().getSqlHelper()
											.addHistory(history);

									psql.deleteById(rep.getId());
									sleep(50);
								} else {
									sleep(50);
									continue;
								}
							} catch (Exception e) {
								e.printStackTrace();
								// try {
								// sleep(50);
								// } catch (InterruptedException e1) {
								// // TODO Auto-generated catch block
								// e1.printStackTrace();
								// }
								continue;
							}
						}
					}
				}
				BizApp.getInstance().isfinish = true;// 开始上传
			}
		}.start();
	}

	/** 上传图片 */
	private ImgPathInfo im(String path) throws Exception {
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		byte[] buf = new byte[8 * 1024];
		CommonBody body = new CommonBody();
		body.setCommand(1);
		body.setImsi(BizApp.getInstance().getIMSI());
		body.setVersion(BizApp.getInstance().getString(R.string.app_version));
		body.setFile("jpg");
		body.setBegin_index(0);
		String reqBody = new Gson().toJson(body);
		reqBody = reqBody + "\r\n\r\n";
		bos.write(reqBody.getBytes("ISO-8859-1"));
		FileInputStream fis = new FileInputStream(path);// "/mnt/sdcard/atsmart/example.jpg");//
		// Bitmap bitmap = BitmapFactory.decodeStream(fis);
		// bitmap.compress(Bitmap.CompressFormat.JPEG, 100,
		// bos);
		for (int readNum; (readNum = fis.read(buf)) != -1;) {
			if (bos.toByteArray().length < 100000) {
				bos.write(buf, 0, readNum);
				length += buf.length;
			} else {
				break;
			}
		}
		bos.write("\r\n\r\n".getBytes("ISO-8859-1"));
		fis.close();
		return new Gson().fromJson(postOnService(bos.toByteArray()),
				ImgPathInfo.class);

	}

	private class ImgPathInfo implements Serializable {
		/**
		 *
		 */
		private static final long serialVersionUID = 7216739021733421705L;
		/**
		 *
		 */
		@SerializedName("file")
		public String path;
	}

	protected String postOnService(byte[] bb) throws MalformedURLException,
			IOException, BizException {
		HttpHelper http = new HttpHelper(bb.length);
		http.setCONNECTION_TIMEOUT(10000);
		http.setREAD_TIMEOUT(10000);
		try {
			http.createMode().url(ServiceHost.uploadImage())
					.header("Content-Type", "charset=ISO-8859-1")
					.header("Accept-Charset", "ISO-8859-1");
			// byte[] bb= reqBody.getBytes("ISO-8859-1");
			http.body(new ByteArrayInputStream(bb)).send();

		} catch (Exception ex) {
			ex.printStackTrace();
			// Will not happen.
		}
		String bodyString = "";
		if (http.isSuccessful()) {
			bodyString = http.getBodyAsString();
			if (bodyString != null) {
				bodyString = bodyString.substring(
						bodyString.indexOf("\r\n\r\n"), bodyString.length());
				return bodyString;
			} else {
				return "";
			}
		} else {
			http.send();
			if (http.isSuccessful()) {
				bodyString = http.getBodyAsString();
				if (bodyString != null) {
					return bodyString;
				} else {
					return "";
				}
			}
			final int responseCode = http.getResponseCode();
			throw new BizException(responseCode);
		}
	}

	/** 返回body */
	private CommonBody body() {
		CommonBody body = new CommonBody();
		body.setCommand(2);
		body.setImsi(BizApp.getInstance().getIMSI());
		body.setVersion(BizApp.getInstance().getString(R.string.app_version));
		return body;
	}

}
